﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.ServiceModel.Web;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web.Security;
using Ashlen.Portal.Core;
using Ashlen.Portal.Data.SqlServer;
using Ashlen.Portal.Core.DataInterfaces;

namespace Ashlen.Portal.Services.Handlers
{
    /// <summary
    /// Summary description for GetAvatarHandler
    /// </summary>
    public class GetAvatarHandler : IHttpHandler
    {
        public MembershipProvider Provider
        {
            get;
            private set;
        }
        private readonly ISecurityDao _securityDao;
        int Width = 0;
        int Height = 0;
        string UserId = string.Empty;

        public GetAvatarHandler()
        {
            Provider = Membership.Provider;
            _securityDao = new SecurityDao();       
        }

        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.Params["height"] != null)
            {
                try
                {
                    Height = int.Parse(context.Request.Params["height"]);
                }
                catch
                {
                    Height = 0;
                }
            }
            if (context.Request.Params["width"] != null)
            {
                try
                {
                    Width = int.Parse(context.Request.Params["width"]);
                }
                catch
                {
                    Width = 0;
                }
            }
            if (context.Request.Params["userid"] != null)
            {
                try
                {
                    UserId = context.Request.Params["userid"];
                }
                catch
                {
                    UserId = string.Empty;
                }
            }

            if (Width >= 0 && Height >= 0 && UserId == string.Empty)
            {
                context.Response.Clear();
                context.Response.ContentType = getContentType(context.Request.PhysicalPath);
                byte[] buffer = getResizedImage(context.Request.PhysicalPath, Width, Height);
                context.Response.OutputStream.Write(buffer, 0, buffer.Length);
                context.Response.End();
        
            }
            else if (Width <= 0 && Height <= 0 && UserId != string.Empty)
            {
                context.Response.Clear();
                context.Response.ContentType = getContentType(context.Request.PhysicalPath); 
                context.Response.WriteFile(context.Request.PhysicalPath);
                context.Response.End();
            }
            else
            {                
                context.Response.Clear();
                context.Response.ContentType = getContentType(context.Request.PhysicalPath);
                byte[] buffer = getResizedImageFromDb(new Guid(UserId), Width, Height);
                context.Response.OutputStream.Write(buffer, 0, buffer.Length);
                context.Response.End();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private byte[] getResizedImageFromDb(Guid userId, int width, int height)
        {
            System.IO.MemoryStream outStream = null;
            var info = _securityDao.GetPersonalInfo(userId) as aspnet_UserPersonalInfo;

            if (info.Avatar == null)
            {
                /* If the user has no image provided, send back a default image */
                if (info.Sex == "M")
                {
                    outStream = new System.IO.MemoryStream(File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/images/PersonMale.png")));
                }
                else
                {
                    outStream = new System.IO.MemoryStream(File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/images/PersonFemale.png")));
                }
            }
            else
            {
                outStream = new System.IO.MemoryStream(info.Avatar);
            }
            Bitmap imgIn = new Bitmap(outStream);

            double y = imgIn.Height;
            double x = imgIn.Width;
            double factor = 1;
            if (width > 0)
            {
                factor = width / x;
            }
            else if (height > 0)
            {
                factor = height / y;
            }

            outStream = new System.IO.MemoryStream();
            Bitmap imgOut = new Bitmap((int)(x * factor), (int)(y * factor));
            Graphics g = Graphics.FromImage(imgOut);
            g.Clear(Color.White);
            g.DrawImage(imgIn, new Rectangle(0, 0, (int)(factor * x), (int)(factor * y)), new Rectangle(0, 0, (int)x, (int)y), GraphicsUnit.Pixel);
            imgOut.Save(outStream, ImageFormat.Jpeg);
            return outStream.ToArray();
        }

        private byte[] getResizedImage(String path, int width, int height)
        {
            using (Bitmap imgIn = new Bitmap(path))
            {
                double y = imgIn.Height;
                double x = imgIn.Width;
                double factor = 1;
                if (width > 0)
                {
                    factor = width / x;
                }
                else if (height > 0)
                {
                    factor = height / y;
                }
                using (System.IO.MemoryStream outStream = new System.IO.MemoryStream())
                {
                    using (Bitmap imgOut = new Bitmap((int)(x * factor), (int)(y * factor)))
                    {
                        Graphics g = Graphics.FromImage(imgOut);
                        g.Clear(Color.White);
                        g.DrawImage(imgIn, new Rectangle(0, 0, (int)(factor * x), (int)(factor * y)), new Rectangle(0, 0, (int)x, (int)y), GraphicsUnit.Pixel);
                        imgOut.Save(outStream, getImageFormat(path));
                        return outStream.ToArray();
                    }
                }
            }
        }

        private string getContentType(String path)
        {
            switch (Path.GetExtension(path))
            {
                case ".bmp": return "Image/bmp";
                case ".gif": return "Image/gif";
                case ".jpg": return "Image/jpeg";
                case ".png": return "Image/png";
                default: break;
            }
            return "";
        }
        
        private ImageFormat getImageFormat(String path)
        {
            switch (Path.GetExtension(path))
            {
                case ".bmp": return ImageFormat.Bmp;
                case ".gif": return ImageFormat.Gif;
                case ".jpg": return ImageFormat.Jpeg;
                case ".png": return ImageFormat.Png;
                default: break;
            }
            return ImageFormat.Jpeg;
        }
    }
}